package cn.jingyuan.bee.utils.io.resource;

import cn.jingyuan.bee.utils.CharsetUtils;
import cn.jingyuan.bee.utils.StringUtils;
import cn.jingyuan.bee.utils.io.IORuntimeException;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * 基于 byte[] 的资源获取器<br>
 * 注意：此对象中 getUrl 方法始终返回 null
 */
public class BytesResource implements Resource, Serializable {

    private final byte[] bytes;

    private final String name;

    /**
     * 构造
     *
     * @param bytes 字节数组
     */
    public BytesResource(byte[] bytes) {
        this(bytes, null);
    }

    /**
     * 构造
     *
     * @param bytes 字节数组
     * @param name 资源名称
     */
    public BytesResource(byte[] bytes, String name) {
        this.bytes = bytes;
        this.name = name;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public URL getUrl() {
        return null;
    }

    @Override
    public InputStream getStream() {
        return new ByteArrayInputStream(this.bytes);
    }

    @Override
    public BufferedReader getReader(Charset charset) {
        return new BufferedReader(new StringReader(readString(charset)));
    }

    @Override
    public String readString(Charset charset) throws IORuntimeException {
        return StringUtils.string(this.bytes, charset);
    }

    @Override
    public String readUtf8String() throws IORuntimeException {
        return readString(CharsetUtils.CHARSET_UTF_8);
    }

    @Override
    public byte[] readBytes() throws IORuntimeException {
        return this.bytes;
    }

}
